import { Form, Modal, message } from 'antd';
import React, { forwardRef, useEffect, useImperativeHandle, useState } from 'react';
import UploadFile from "@/components/FileUpload";
import { updateShop } from '../service';

interface IRef {
  edit?: () => any;
  callback?: () => any;
}

const AddModal: React.ForwardRefRenderFunction<IRef, any> = (props, ref) => {

  const [form] = Form.useForm();
  const [modalVisible, setModalVisible] = useState(false);
  const [btnLoading, setBtnLoading] = useState<boolean>(false);
  const [editRow, setEditRow] = useState<any | null>(null);

  const { callback } = props;

  /**
 * 添加节点
 * @param fields
 */
  const updateItem = async (fields: any, id: any) => {
    setBtnLoading(true);
    const isAdd = !id;
    const txt = isAdd ? '添加' : '编辑';
    const params = { ...fields };
    if (!isAdd) {
      Object.assign(params, { id });
    }
    try {
      await updateShop(params);
    } catch (error) {
      message.error(`${txt}失败请重试！`);
      return false;
    } finally{
      setBtnLoading(false)
    }
  };


  const handleCancel = () => {
    setModalVisible(false);
    form.resetFields(['logo']);
  };

  const getInitialValues = async (row: any) => {
    if (row) form.setFieldsValue(row);
  };

  // 关闭弹窗 去掉loading
  useEffect(() => {
    if (!modalVisible) setBtnLoading(false);
  }, [modalVisible]);

  useImperativeHandle(ref, () => ({
    edit: (row?: any) => {
      setEditRow(row);
      if (row) getInitialValues(row);
      setModalVisible(true);
    }
  }));

  const handleOk = () => {
    console.log(111);
    form.validateFields().then((data) => {
      updateItem(data, editRow?.id).then(() => {
        setModalVisible(false);
        message.success('更新LOGO成功')
        callback?.();
      });
    })
  };

  return (
    <>
      <Modal
        title={
          editRow
            ? '编辑LOGO'
            : '新增LOGO'
        }
        onCancel={handleCancel}
        onOk={handleOk}
        visible={modalVisible}
        width={640}
        maskClosable={false}
        okButtonProps={{
          loading: btnLoading
        }}
        >
        <Form form={form} labelCol={{ span: 4 }} wrapperCol={{ span: 16 }} >
          <Form.Item name={'logo'} label='logo'>
            <UploadFile fileName={[{ url: editRow?.logo, name: editRow?.logo }]} />
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};

export default forwardRef(AddModal);
